package me.huangxiang.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ProducerAndConsumerDemo {
    private static LinkedBlockingQueue<Integer> linkedBlockingQueue = new LinkedBlockingQueue<>(100);
    private static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static class Producer implements Runnable{

        @Override
        public void run() {
            Integer x = atomicInteger.incrementAndGet();
            try {
                linkedBlockingQueue.put(x);
                System.out.println(Thread.currentThread().getId() + "生产了编号为：" + x + "的商品");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static class Consumer implements Runnable{

        @Override
        public void run() {
            try {
                Integer x = linkedBlockingQueue.take();
                System.out.println(Thread.currentThread().getId() + "消费者消费了编号为：" + x + "的商品");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);
        for (int i = 0; i < 8; i++){
            threadPool.scheduleAtFixedRate(new Producer(), 1, 1, TimeUnit.SECONDS);
        }
//        threadPool.scheduleAtFixedRate(new Producer(), 1, 1, TimeUnit.SECONDS);

        threadPool.scheduleAtFixedRate(new Consumer(), 500, 500, TimeUnit.MICROSECONDS);
    }
}
